package com.db.adjust.algorithm.adj4;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class codesign {

    private static String Fixed_Hex_key = "219ab81af03a28fced31ce64e105fdb4f72f042edd5500d3205bb84aef64d994";
    private static String Fixed_salt = "9A99ECBD9CBE03994D91E128E86F4A187F1CBC35";
    private static String Fixed_Hex_HmacKey = "0321d2e734b050321635278869a79418a48443b2adbe4cb656651edba9829265";

    public static String nSign(Map map) throws Exception {
//    public static byte[] nSign(String MapStr) throws Exception {
        String Random_Hex_iv = "3dc282b910b2e180a87169e100352cf6";
        StringBuilder sb = new StringBuilder();
//        Map<String, String> map = stringToMap(MapStr);
        int len = keys.length;
        for (int i = 0; i < len; i++) {
            String key = keys[i];
            //System.out.println(key);
            if (map.containsKey(key)) {
                System.out.println(key + " : " + map.get(key));
                System.out.println();
                sb.append(map.get(key));
            } else if (key != null && key.equals("secondary_dedupe_token")) {
                sb.append("1000000");
            }
        }
        String do_Sha256_HexStr = AESUtil.bytesToHex(Fixed_salt.getBytes()) + "0000000000000000" + AESUtil.bytesToHex(sb.toString().getBytes());
        String do_Sha256Encrypt_Final_HexStr = AESUtil.bytesToHex(MagicSHA256.MagicHash(AESUtil.hexToByteArray(do_Sha256_HexStr)));
        String do_AES_HexStr = "{\"a\":0,\"b\":\"" + do_Sha256Encrypt_Final_HexStr.toUpperCase() + "\",\"c\":\"" + Fixed_salt.toUpperCase() + "\"}";
        String do_AESEncrypt_Final_HexStr = AESUtil.encryptAES(AESUtil.bytesToHex(do_AES_HexStr.getBytes()) + "00" + "0202", Fixed_Hex_key, Random_Hex_iv);//手动填充pkcs7
        String do_HmacEncrypt_Final_HexStr = HmacSHA256.sha256_HMAC(do_AESEncrypt_Final_HexStr, Fixed_Hex_HmacKey);
        String Hex_Final = Random_Hex_iv + do_AESEncrypt_Final_HexStr + do_HmacEncrypt_Final_HexStr;
//        System.out.println(Hex_Final);
//        byte[] Final = AESUtil.hexToByteArray(Hex_Final);
//        return Final;
        return Hex_Final.toUpperCase();
    }

    public static Map<String, String> stringToMap(String input) {
        Map<String, String> map = new HashMap<>();

        // 去掉字符串两端的大括号
        input = input.substring(1, input.length() - 1);

        // 根据逗号和空格分割字符串
        String[] keyValuePairs = input.split(", ");

        for (String pair : keyValuePairs) {
            // 根据等号分割键值对
            //String[] entry = pair.split("=");
            // 将键值对放入到 Map 中
            map.put(getValueBeforeFirstEquals(pair), getValueAfterFirstEquals(pair));
        }

        return map;
    }

    public static String getValueAfterFirstEquals(String input) {
        int index = input.indexOf("="); // 查找第一个等号的位置
        if (index != -1 && index + 1 < input.length()) {
            return input.substring(index + 1); // 获取等号右侧的数据
        } else {
            return null; // 如果没有找到等号或等号右侧没有数据，返回null
        }
    }

    public static String getValueBeforeFirstEquals(String input) {
        int index = input.indexOf("="); // 查找第一个等号的位置
        if (index != -1) {
            return input.substring(0, index); // 获取等号左侧的数据
        } else {
            return null; // 如果没有找到等号，返回null
        }
    }

    public static String readLineFromFile(String filePath, int lineNumber) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            int currentLine = 0;
            while ((line = reader.readLine()) != null) {
                currentLine++;
                if (currentLine == lineNumber) {
                    return line;
                }
            }
        }
        return null; // 如果没有找到对应的行，返回 null
    }

    public static void main(String[] args) throws Exception {
        // frida hook :  NativeLibHelper.nSign is called: context=ru.rivegauche.app.App@fc0d8c9, obj={gps_adid_attempt=1, country=CN, api_level=28, event_buffering_enabled=0, hardware_name=PPR1.180610.011.G950FXXUCDUD1, app_version=3.21.2-gms, app_token=gxuvxpud5la8, installed_at=2024-03-19T18:06:36.731Z+0800, session_length=0, created_at=2024-03-20T11:11:59.528Z+0800, device_type=phone, language=zh, gps_adid=49d60962-30dc-4354-ac28-363dbc2a99d5, connectivity_type=1, mcc=460, device_manufacturer=samsung, display_width=1080, time_spent=0, google_app_set_id=cfd51ca9-e690-1185-4c1d-af7b30cee046, device_name=SM-G950F, needs_response_details=1, os_build=PPR1.180610.011, updated_at=2024-03-19T18:06:36.731Z+0800, cpu_type=arm64-v8a, screen_size=normal, screen_format=long, gps_adid_src=service, subsession_count=1, mnc=00, os_version=9, android_uuid=aec2d556-28e6-416f-8609-c30eaa177f8f, last_interval=50, environment=production, screen_density=high, attribution_deeplink=1, session_count=1, display_height=2076, package_name=ru.rivegauche.app, os_name=android, ui_mode=1, activity_kind=session, client_sdk=android4.35.1, tracking_enabled=1}, bArr=-117,-1,74,19,106,-12,-76,-74,-84,84,-125,-73,5,45,-65,72,98,45,92,-50,25,88,-28,-48,68,89,33,17,-53,-85,-108,-4, i=28
        // frida hook result:  G/Hnqo1Hzd7hwi4nP9Y62JP/kr3aHRJdbh7RedoiS6nm4gwzp9swFOQt5q8XXmV66O1YYhN6OluttLbsZN7Mt3uJaFvsVZWUY8xx3gcSx9yMK8cON3gcMGJV/BfMOHaVbWi/sdKYvTARAwNfasA6INx9zL/eCPMVYOYaaa2SfIStj7N0i10B0igIuA3AdCV5VmsZOn7xAgV7s8LeXYOeBxz94ShkjH7GMJGI1fkNlAQ=

//        String aaa = "{updated_at=2024-03-18T18:20:44.071Z+0800, device_type=phone, device_manufacturer=LGE, google_app_set_id=3eaa55a8-cb6e-426e-8b1d-98c140207961, environment=production, session_count=1, attribution_deeplink=1, android_uuid=30f690c8-e499-45db-98b0-c6b07058010d, connectivity_type=1, os_build=NBD90Z, api_level=24, needs_response_details=1, event_buffering_enabled=0, os_name=android, android_id=fb368793f898802a, display_width=1080, screen_format=normal, activity_kind=session, screen_density=high, hardware_name=aosp_hammerhead-userdebug 7.0 NBD90Z eng.clyde.20161005.215320 test-keys, package_name=ru.rivegauche.app, client_sdk=android4.35.1, app_version=3.21.2-gms, installed_at=2024-03-18T18:20:44.071Z+0800, country=CN, screen_size=normal, app_token=gxuvxpud5la8, device_name=Nexus 5, ui_mode=1, created_at=2024-03-20T10:25:12.352Z+0800, display_height=1786, os_version=7.0, language=zh, cpu_type=armeabi-v7a}";
//        nSign(aaa);
    }


    public static String[] keys = {
            "ad_impressions_count",
            "ad_revenue_network",
            "ad_revenue_placement",
            "ad_revenue_unit",
            "adgroup",
            "android_id",
            "android_uuid",
            "api_level",
            "app_secret",
            "app_token",
            "app_version",
            "app_version_short",
            "att_status",
            "bundle_id",
            "callback_params",
            "campaign",
            "click_time",
            "click_time_server",
            "country",
            "created_at",
            "creative",
            "currency",
            "deduplication_id",
            "default_tracker",
            "details",
            "device_known",
            "device_name",
            "device_type",
            "environment",
            "event_callback_id",
            "event_count",
            "event_token",
            "external_device_id",
            "fb_anon_id",
            "fb_id",
            "fire_adid",
            "fire_tracking_enabled",
            "found_location",
            "google_play_instant",
            "gps_adid",
            "gps_adid_src",
            "granular_third_party_sharing_options",
            "hardware_name",
            "idfa",
            "idfv",
            "initiated_by",
            "install_begin_time",
            "install_begin_time_server",
            "install_version",
            "installed_at",
            "mcc",
            "measurement",
            "mnc",
            "needs_cost",
            "os_build",
            "os_name",
            "os_version",
            "package_name",
            "params",
            "partner_params",
            "partner_sharing_settings",
            "payload",
            "primary_dedupe_token",
            "purchase_time",
            "push_token",
            "referrer",
            "referrer_api",
            "reftag",
            "revenue",
            "sales_region",
            "secondary_dedupe_token",
            "session_count",
            "session_length",
            "sharing",
            "skadn_registered_at",
            "source",
            "started_at",
            "subsession_count",
            "time_spent",
            "tracker",
            "tracking_enabled",
            "updated_at",
            "activity_kind",
            "client_sdk"
    };

}
